﻿// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Echo.Client
{
    using System;
    using System.Text;
    using CNative.Logging;
    using DotNetty.Buffers;
    using DotNetty.Transport.Channels;
    using Examples.Common;
    using Microsoft.Extensions.Logging;

    public class EchoClientHandler : ChannelHandlerAdapter
    {
        readonly IByteBuffer initialMessage; 
        private readonly ILogger _logger = new ConfigLogger();//LoggingHelper.Logger;

        public EchoClientHandler()
        {
            this.initialMessage = Unpooled.Buffer(ClientSettings.Size);
            byte[] messageBytes = Encoding.UTF8.GetBytes("Hello world");
            this.initialMessage.WriteBytes(messageBytes);
        }

        public override void ChannelActive(IChannelHandlerContext context) => context.WriteAndFlushAsync(this.initialMessage);

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var byteBuffer = message as IByteBuffer;
            if (byteBuffer != null)
            {
                //Console.WriteLine("Received from server: " + byteBuffer.ToString(Encoding.UTF8));
                _logger.LogInformation("Received from server: " + byteBuffer.ToString(Encoding.UTF8));
            }
            context.WriteAsync(message);
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            _logger.LogError("Exception: " + exception);
            context.CloseAsync();
        }

        public override void ChannelRegistered(IChannelHandlerContext context)
        {
            _logger.LogInformation("ChannelRegistered: " + context.Channel.Id);
            base.ChannelRegistered(context);
        }

        public override void ChannelUnregistered(IChannelHandlerContext context)
        {
            _logger.LogInformation("ChannelUnregistered: " + context.Channel.Id);
            base.ChannelUnregistered(context);
        }
    }
}